<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DeleteYuanjiang, GetYuanjiangList, PostCreateYuahjiang } from '@/api/modules/yuanjiang'
import GetCacheData from '@/store/modules/NewPageCache'

// const imgDomain = 'https://img1.eprhan.cc'

const cacheData = GetCacheData()
let PageNum = cacheData.GetCacheData('yuanjiang').currentPage

const findFrom = ref({
  ...(cacheData.GetCacheData('yuanjiang').fromData),
})
const dataList: any = ref([])
const loading = ref(true)
const total = ref(0)

// 获取数据
function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.Id && ({ Id: findFrom.value.Id })),
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.Mobile && ({ Mobile: findFrom.value.Mobile })),
    ...(findFrom.value.ParentId && ({ ParentId: findFrom.value.ParentId })),
    ...(findFrom.value.ParentUserId && ({ ParentUserId: findFrom.value.ParentUserId })),
    ...(findFrom.value.RoleId !== '~' && ({ RoleId: findFrom.value.RoleId })),
    ...(findFrom.value.Status !== '~' && ({ Status: findFrom.value.Status })),
  }
  GetYuanjiangList(params).then((res: any) => {
    if (res.statusCode === 200) {
      dataList.value = res.data.items
      total.value = res.data.total
      loading.value = false
    }
    else {
      ElMessage.error('获取数据失败')
      loading.value = false
    }
  })
}

// 删除
function Delete(id: any) {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    DeleteYuanjiang(id).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('删除成功')
        GetDataList()
      }
      else {
        ElMessage.error(`删除失败。${res.errors}`)
      }
    })
  })
}

const formVisible = ref(false)
const form = reactive ({
  mobiles: '',
})

function StartEntering() {
  form.mobiles = ''
  formVisible.value = true
}

function EndEntering() {
  if (form.mobiles === '') {
    ElMessage.error('请输入手机号')
    return
  }
  const params = {
    mobiles: form.mobiles.split(/[，,、\s]+/),
  }
  // console.log(params)

  PostCreateYuahjiang(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('录入成功')
      GetDataList()
      formVisible.value = false
    }
    else {
      ElMessage.error('录入失败')
    }
  })
}

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('yuanjiang').currentSize)
  cacheData.SetCacheData('yuanjiang', PageNum, cacheData.GetCacheData('yuanjiang').currentSize, findFrom.value)
}

// 页码
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('yuanjiang', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('yuanjiang').currentSize)
  cacheData.SetCacheData('yuanjiang', val, cacheData.GetCacheData('yuanjiang').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('yuanjiang').currentPage || 1
})

onMounted(async () => {
  GetDataList(cacheData.GetCacheData('yuanjiang').currentPage, cacheData.GetCacheData('yuanjiang').currentSize)
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="ID">
                <el-input v-model="findFrom.Id" type="number" placeholder="请输入ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" type="number" placeholder="请输入用户ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="手机号码">
                <el-input v-model="findFrom.Mobile" type="number" placeholder="请输入手机号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="上级援疆会员ID">
                <el-input v-model="findFrom.ParentId" type="number" placeholder="请输入上级援疆会员ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="上级用户ID">
                <el-input v-model="findFrom.ParentUserId" type="number" placeholder="请输入上级用户ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="角色">
                <el-select v-model="findFrom.RoleId" placeholder="请选择角色">
                  <el-option label="不限" value="~" />
                  <el-option label="援疆会员" :value="1" />
                  <el-option label="亲友团" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="findFrom.Status" placeholder="请选择状态">
                  <el-option label="全部" value="~" />
                  <el-option label="待激活" :value="0" />
                  <el-option label="正常" :value="1" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="StartEntering">
          批量录入会员
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList" stripe style="width: 100%;" border>
        <el-table-column align="center" width="100" prop="id" label="ID" />
        <el-table-column align="center" prop="subscriber.userId" label="用户ID" width="120" />
        <el-table-column align="center" prop="subscriber" label="用户信息" width="300">
          <template #default="scope">
            <div v-if="!scope.row.subscriber">
              未授权
            </div>
            <div v-else class="user-name">
              <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriber?.userAvatar" />
              <div>
                <p style="margin: 0;">
                  {{ scope.row.subscriber?.userNickName }}
                </p>
                <span>
                  {{ scope.row.subscriber?.userPhone }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="300" prop="subscriber.scOpenId" label="用户OpenId" />
        <el-table-column align="center" width="300" prop="subscriber.unionId" label="用户unionId" />
        <el-table-column align="center" width="140" prop="roleId" label="角色">
          <template #default="scope">
            <el-tag>
              {{ scope.row.roleId === 1 ? '援疆会员'
                : scope.row.roleId === 2 ? '亲友团' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="parentId" label="上级援疆会员ID" width="140" />
        <el-table-column align="center" prop="parent.userId" label="上级用户ID" width="140" />
        <el-table-column align="center" prop="parent" label="上级用户信息" width="300">
          <template #default="scope">
            <div v-if="scope.row.parent.userId === 0">
              未授权
            </div>
            <div v-else class="user-name">
              <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.parent?.userAvatar" />
              <div>
                <p style="margin: 0;">
                  {{ scope.row.parent?.userNickName }}
                </p>
                <span>
                  {{ scope.row.parent?.userPhone }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="300" prop="parent.scOpenId" label="上级用户OpenId" />
        <el-table-column align="center" width="300" prop="parent.unionId" label="上级用户unionId" />
        <el-table-column align="center" width="140" prop="status" label="状态">
          <template #default="scope">
            <el-tag>
              {{ scope.row.status === 0 ? '待激活'
                : scope.row.status === 1 ? '正常' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column header-align="center" width="240" prop="desp" label="描述" />
        <el-table-column align="center" width="240" prop="bindTime" label="绑定身份时间" />
        <el-table-column align="center" width="240" prop="addTime" label="添加时间" />
        <el-table-column align="center" width="240" prop="updateTime" label="修改时间" />
        <el-table-column align="center" label="操作" fixed="right" min-width="140">
          <template #default="scope">
            <div style="line-height: 42px;">
              <el-button type="danger" @click="Delete(scope.row.id)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('yuanjiang').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :default-current-page="nowPageNum"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>

    <el-dialog v-model="formVisible" title="批量录入" width="500">
      <el-form :model="form">
        <el-form-item label="录入（用逗号、顿号、空格、回车等隔开）" label-position="top">
          <el-input
            v-model="form.mobiles" type="textarea" style="width: 450px;"
            :autosize="{ minRows: 2, maxRows: 8 }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="EndEntering">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;
  margin-right: 25px;

  div {
    text-align: left;
  }
}
</style>
